package com.example.demo.controller;

import cn.hutool.json.JSONUtil;
import com.example.demo.entity.Activity;
import com.example.demo.entity.Expense;
import com.example.demo.entity.Fee_list;
import com.example.demo.pojo.PlannerResult;
import com.example.demo.repository.ActivityRepository;
import com.example.demo.repository.ExpenseRepository;
import com.example.demo.repository.Fee_listRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.utils.ThreadLocalUtil;
import com.example.demo.vo.ExpenseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/expense")
public class ExpenseController {

    @Autowired
    ExpenseRepository expenseRepository;
    @Autowired
    private ActivityRepository activityRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private Fee_listRepository fee_listRepository;

    /*
    @PostMapping("/findall")
    public List<Expense> findAll()
    {
        return expenseRepository.findAll();
    }

    @GetMapping("/findexpensebyid/{id}")
    public Expense findExpenseById(@PathVariable("id") Integer id)
    {
        return expenseRepository.findById(id).get();
    }
    @PutMapping("/update")
    public String update(@RequestBody Expense expense){
        Expense result =expenseRepository.save(expense);
        if(result !=null)
        {
            return "success";
        }
        else {
            return "error";
        }
    }

    @DeleteMapping("/deletebyid/{id}")
    public  void deleteByid(@PathVariable("id")  Integer id){
        expenseRepository.deleteById(id);

    }

     */

    @PostMapping("/save")
    public PlannerResult<String> createexpense(@RequestBody ExpenseVo expenseVo)
    {
        System.out.println(expenseVo);

        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = -1;
        if (claims != null) {
            // 获取 userId 信息
             userId = (Integer) claims.get("id");
        }
        Expense expense=new Expense();
        expense.setActivity_id(expenseVo.getActivity_id());
        expense.setUser_id(userId);
        expense.setState(0);
        expense.setAmount(expenseVo.getAmount());
        expense.setReason(expenseVo.getReason());
        Expense result=expenseRepository.save(expense);

        if(result.getState() != null)
        {
            return PlannerResult.success();
        }
        else {
            return PlannerResult.error("提交失败");
        }
    }

    //供给用户调用查看自己的报销
    @GetMapping("/myexpense")
    public PlannerResult<List<ExpenseVo>> my_expense(@RequestParam("type") Integer type) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        List<ExpenseVo> expenseVos = new ArrayList<ExpenseVo>();
        ExpenseVo expenseVo = new ExpenseVo();
            if (claims != null) {
                // 获取 userId 信息
                Integer userId = (Integer) claims.get("id");
                if(type.equals(1)) {
                    List<Expense> expenseList = expenseRepository.findByUserId(userId);
                    expenseList.forEach(expense -> {
                        expenseVo.setActivity_name(activityRepository.findById(expense.getActivity_id()).get().getName());
                        expenseVo.setUsername(userRepository.findById(expense.getUser_id()).get().getUsername());
                        expenseVo.setAmount(expense.getAmount());
                        expenseVo.setReason(expense.getReason());
                        expenseVo.setState(expense.getState());
                        expenseVo.setId(expense.getId());

                        expenseVos.add(expenseVo);
                    });
                    return PlannerResult.success(expenseVos);
                }
                else {
                    List<Activity> byCreator = activityRepository.findByCreator(userId);
                    List<Expense> expenseList = expenseRepository.findByActivityId(byCreator.stream().map(Activity::getId).collect(Collectors.toList()));
                    System.out.println(expenseList);
                    for (Expense expense : expenseList){
                        ExpenseVo expenseVo_ = new ExpenseVo();
                        BeanUtils.copyProperties(expense,expenseVo_);
                        expenseVo_.setActivity_name(activityRepository.findById(expense.getActivity_id()).get().getName());
                        expenseVo_.setUsername(userRepository.findById(expense.getUser_id()).get().getUsername());

                        expenseVos.add(expenseVo_);
                    }

//                    expenseList.forEach(expense -> {
//                        expenseVo.setActivity_name(activityRepository.findById(expense.getActivity_id()).get().getName());
//                        expenseVo.setUsername(userRepository.findById(expense.getUser_id()).get().getUsername());
//                        expenseVo.setAmount(expense.getAmount());
//                        expenseVo.setReason(expense.getReason());
//                        expenseVo.setState(expense.getState());
//                        expenseVo.setId(expense.getId());
//
//                        expenseVos.add(expenseVo);
//                    });
                    System.out.println(expenseVos);
                    return PlannerResult.success(expenseVos);
                }
            }
            else {
                return PlannerResult.error("未登录");
            }
    }

    @PutMapping("/check")
    public PlannerResult<String> check(@RequestParam("id") Integer id, @RequestParam("state") Integer state) {
        Expense expense = expenseRepository.findById(id).get();
        expense.setState(state);
        Expense result = expenseRepository.save(expense);

        /*写入费用清单*/
        if(result.getState().equals(1)){
            Fee_list fee_list = new Fee_list();
            fee_list.setActivity_id(expense.getActivity_id());
            fee_list.setFee(expense.getAmount());
            fee_list.setContext(expense.getReason());

            fee_listRepository.save(fee_list);
        }

        if (result.getId() != null) {
            return PlannerResult.success();
        } else {
            return PlannerResult.error("审核失败");
        }

    }
}
